package com.example.springbootdemo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.springbootdemo.bean.ApiKeyContext;
import com.example.springbootdemo.bean.kernelApi.Result;
import com.example.springbootdemo.config.GlobalVariables;
import com.example.springbootdemo.config.JHConfig;
import com.example.springbootdemo.dto.comparefile.ThingHistoryFileData;
import com.example.springbootdemo.dto.comparefile.ThingHistoryFileObj;
import com.example.springbootdemo.dto.createWorkInstance.DataDetail;
import com.example.springbootdemo.po.JinhuaProject;
import com.example.springbootdemo.response.ApiResponse;
import com.example.springbootdemo.response.ProjectData;
import com.example.springbootdemo.response.ResultData;
import com.example.springbootdemo.service.HistoryService;
import com.example.springbootdemo.service.ProjectService;
import com.example.springbootdemo.utils.Md5Utils;
import com.example.springbootdemo.utils.ReadFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/jinhua")
@Slf4j
public class ProjectController {
    //获取申报中的项目数据接口
    public static String GET_PROCESSING_PROJECT = "/egovProject/egovApi/getProcessingProject.shtml";

    //获取发布的项目数据接口
    public static String GET_PUBLISH_PROJECT = "/egovProject/egovApi/getPublishProject.shtml";

    //下载附件
    public static String DOWN_LOAD_ATTR = "/sys/download/downLoadAttr.shtml";

    public static String DOWN_LOAD_PATH="D:\\jhfile\\";

    @Autowired
    JHConfig jhConfig;

    private final GlobalVariables globalVariables;
    private RestTemplate restTemplate = new RestTemplate();

    @Autowired
    HistoryService historyService;

    @Autowired
    public ProjectController(GlobalVariables globalVariables) {
        this.globalVariables = globalVariables;
    }

    /**
     * 获取申报中的项目数据接口
     */
/*    @GetMapping("/getProcessingProject")
    public ProjectData getProcessingProject() {
        try {
            String apiSecret = globalVariables.getApiSecret();
            //请求地址
            String url = jhConfig.getUrl() + GET_PROCESSING_PROJECT;
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("appId", jhConfig.getAppId());
            long timeMillis = System.currentTimeMillis();
            params.add("requestTime", timeMillis + "");
            //用MD5加密的字符串(字母全部小写)， MD5 (系统应用ID+应用秘钥+发出请求时时间戳)
            String token = Md5Utils.hash(jhConfig.getAppId() + apiSecret + timeMillis);
            params.add("token", token);
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
            //请求接口
            ApiResponse apiResponse = restTemplate.postForObject(url, requestEntity, ApiResponse.class);
            if (null != apiResponse) {
                if (apiResponse.getSuccess() && "200".equals(apiResponse.getStatus())) {
                    //返回
                    ProjectData projectData = JSON.parseObject(JSON.toJSONString(apiResponse.getData()), ProjectData.class);
                    List<JinhuaProject> list = projectData.getList();
                    for (JinhuaProject jinhuaProject : list) {
                        jinhuaProject.setType(1L);
                    }
                    return projectData;
                }else {
                    log.error("获取数据失败，错误信息{}",apiResponse.getMsg());
                }
            }
        } catch (Exception e) {
            log.error("获取申报中的项目数据接口异常：{}", e.getMessage());
        }
        return null;
    }*/


    public List<JinhuaProject>  getPublishProject(List<JinhuaProject> jinhuaProjects,int pageNo) {
        try {
            String apiSecret = globalVariables.getApiSecret();
            //请求地址
            String url = jhConfig.getUrl() + GET_PUBLISH_PROJECT;
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("appId", jhConfig.getAppId());
            long timeMillis = System.currentTimeMillis();
            params.add("requestTime", timeMillis + "");
            //用MD5加密的字符串(字母全部小写)， MD5 (系统应用ID+应用秘钥+发出请求时时间戳)
            String token = Md5Utils.hash(jhConfig.getAppId() + apiSecret + timeMillis);
            params.add("token", token);
            params.add("page.next", pageNo + "");
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
            //请求接口
            ApiResponse apiResponse = restTemplate.postForObject(url, requestEntity, ApiResponse.class);
            if (null != apiResponse) {
                if (apiResponse.getSuccess() && "200".equals(apiResponse.getStatus())) {
                    //返回
                    ProjectData projectData = JSON.parseObject(JSON.toJSONString(apiResponse.getData()), ProjectData.class);
                    List<JinhuaProject> list = projectData.getList();
                    for (JinhuaProject jinhuaProject : list) {
                        jinhuaProject.setType(2L);
                        //文件下载,读取内容，上传到奥吉能历史任务表记录

                    }
                    jinhuaProjects.addAll(list);
                    if (projectData.getHasNext()) {
                        getPublishProject(jinhuaProjects,pageNo+1);
                    }
                    return jinhuaProjects;
                }else {
                    log.error("获取数据失败，错误信息{}",apiResponse.getMsg());
                }
            }
        } catch (Exception e) {
            log.error("获取发布的项目数据接口--定时任务异常：{}", e.getMessage());
        }
        return null;
    }

    /**
     * 获取发布的项目数据接口
     */
    @GetMapping("/getPublishProject")
    public ResultData getTotalData(ProjectData projectData){
        List<JinhuaProject> jinhuaProjects = new ArrayList<>();
        List<JinhuaProject> publishProject = getPublishProject(jinhuaProjects, 1);

        //批量设置id
        ArrayList<DataDetail> dataDetails = new ArrayList<>();
        for (JinhuaProject item:publishProject){
            if (null!=item.getConstructionPlan()){
                DataDetail dataDetail = fileDownload(item);
                dataDetails.add(dataDetail);
            }
        }

        //查询奥技能历史文件表进行更新或者新增
        com.example.springbootdemo.dto.comparefile.ResultData ajnHistoryList = historyService.getAJNHistoryList();
        ThingHistoryFileObj data = ajnHistoryList.getData();
        List<ThingHistoryFileData> historyFileDataList = data.getData();
        //这里再对查询奥技能的数据处理一下，还是因为有脏数据，影响程序执行
        ArrayList<ThingHistoryFileData> finalThingHistoryFileData = new ArrayList<>();
        for (ThingHistoryFileData finalThingHistoryFileDataItem:historyFileDataList){
            if (null!=finalThingHistoryFileDataItem.getProjectId()){
                finalThingHistoryFileData.add(finalThingHistoryFileDataItem);
            }
        }
        //查询奥技能的历史文件表单数据，dataDataItem是从大数据拉去下来的数据并且是能读取到文件内容封装的数据，然后需要新增到奥技能，有的更新，没有的新增
        //也就奥技能表单过滤不到直接新增，过滤到的拿到奥技能平台当前数据的唯一标识id赋值到datadetailitem进行更新
        for (DataDetail dataDetailItem:dataDetails){
            List<ThingHistoryFileData> ajnCollect = finalThingHistoryFileData.stream().filter(thingHistoryFileData ->
                    //存在脏数据，这里需要预防一下，先随便给个值吧，给控制
                    thingHistoryFileData.getProjectId().equals(dataDetailItem.getFileId()))
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(ajnCollect)){
                //更新此dataDetailItem,赋值奥技能平台的唯一标识，这样调用新增接口，即更新数据
                //这里存在一个问题，就是奥技能无法删除数据，存在脏数据，理论上过滤出来的数据只有唯一一条，这里默认先这样处理
                dataDetailItem.setId(ajnCollect.get(0).getId());
            }
        }

        System.out.println(dataDetails);
        //一条条新增到奥集能
        for (DataDetail item:dataDetails){
            Result historyToAJN = historyService.createHistoryToAJN(item);
            if (historyToAJN.getCode()== HttpStatus.SC_OK){
                log.info("创建成功,项目id为：{}",item.getFileId());
            }else {
                log.error("新增奥技能历史任务表失败，失败原因{}",historyToAJN.getMsg());
            }
        }

        ResultData resultData = new ResultData();
        resultData.setTotal(publishProject.size());
        resultData.setJinhuaProjects(publishProject);
        return resultData;
    }

    private DataDetail fileDownload(JinhuaProject jinhuaProject) {
        String constructionPlan = jinhuaProject.getConstructionPlan();
        JSONObject jsonData = JSONObject.parseObject(constructionPlan);
        String name = jsonData.get("name").toString();
        String id = jsonData.get("id").toString();
        String fileDownloadUrl = jhConfig.getUrl() + DOWN_LOAD_ATTR + "?id=" + id;
        byte[] bytes = restTemplate.getForObject(fileDownloadUrl, byte[].class);
        if (bytes != null && bytes.length > 0) {
            // //下载文件到本地
            String filePath = DOWN_LOAD_PATH + id + name;
            BufferedOutputStream bos = null;
            FileOutputStream fos = null;
            File file = null;
            try {

                file = new File(filePath);
                if (!file.getParentFile().exists()) {
                    //文件夹不存在 生成
                    file.getParentFile().mkdirs();
                }
                fos = new FileOutputStream(file);
                fos.write(bytes);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        //读取下载的文件内容返回
        try {
            String filePath = DOWN_LOAD_PATH + id + name;
            String s = ReadFileUtil.readFile(new File(filePath));
            DataDetail dataDetail = new DataDetail();
            dataDetail.setFileContent(s);
            dataDetail.setFileName(name);
            dataDetail.setFileId(jinhuaProject.getID());
            dataDetail.setFilePath(filePath);
            dataDetail.setName("historyFile");
            return dataDetail;
        } catch (IOException e) {
            log.error("读取下载的文件异常");
            throw new RuntimeException(e);
        }
        //其他附件下载
      /*  String otherFile = jinhuaProject.getOtherFile();
        if (StringUtils.isNotBlank(otherFile)) {
            JSONArray jsonArray = JSONArray.parseArray(otherFile);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String fileName = jsonObject.get("name").toString();
                String fileId = jsonObject.get("id").toString();
                String fileDownloadOtherUrl = jhConfig.getUrl() + DOWN_LOAD_ATTR + "?id=" + fileId;
                byte[] otherFileBytes = restTemplate.getForObject(fileDownloadOtherUrl, byte[].class);
                if (bytes != null && bytes.length > 0) {
                    //下载文件到本地
                    String filePath = DOWN_LOAD_PATH + fileId + fileName;
                    BufferedOutputStream bos = null;
                    FileOutputStream fos = null;
                    File file = null;
                    try {

                        file = new File(filePath);
                        if (!file.getParentFile().exists()) {
                            //文件夹不存在 生成
                            file.getParentFile().mkdirs();
                        }
                        fos = new FileOutputStream(file);
                        fos.write(bytes);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }

            }
        }*/

    }

}
